import { colorMix } from '@/utils/color'
import XEUtils from 'xe-utils'
import { deepMerge } from '@/utils'
import { getThemeColor } from '../../../helper/theme'
export const rankPiecewiseVisualMap = (options, systemConfig, isMap = false, isPrimary = false) => {
  const initOptions: any = options
  const chartThemeColor = getThemeColor(systemConfig)
  if (initOptions.series && initOptions.series.length > 0 && initOptions.series[0].data && initOptions.series[0].data.length > 0) {
    const maxNum = isMap ? (initOptions.series[0].data[0]?.value ?? 0) : parseInt(XEUtils.max(initOptions.series[0].data, '')?.toString() ?? '0')
    let minAverage = 0
    let pieces: any = []
    if (maxNum >= 4) {
      const avgNum: number = Math.trunc(maxNum / 4)
      const avgLength = avgNum.toString().length
      const avgFirstNum = parseInt(avgNum.toString().split('')[0])
      if (avgLength >= 2) {
        minAverage = avgFirstNum * Math.pow(10, avgLength - 1)
      } else {
        minAverage = avgFirstNum
      }
      pieces = [
        { gte: minAverage * 4, label: '≥' + minAverage * 4, color: isMap && isPrimary ? colorMix(chartThemeColor[0], '#000000', 0.3) : chartThemeColor[0] },
        { gte: minAverage * 3, lt: minAverage * 4, label: minAverage * 3 + '-' + minAverage * 4, color: isMap && isPrimary ? chartThemeColor[0] : chartThemeColor[1] },
        { gte: minAverage * 2, lt: minAverage * 3, label: minAverage * 2 + '-' + minAverage * 3, color: isMap && isPrimary ? colorMix(chartThemeColor[0], '#ffffff', 0.3) : chartThemeColor[2] },
        { gte: minAverage, lt: minAverage * 2, label: minAverage + '-' + minAverage * 2, color: isMap && isPrimary ? colorMix(chartThemeColor[0], '#ffffff', 0.5) : chartThemeColor[3] },
        { lt: minAverage, label: '0-' + minAverage, color: isMap && isPrimary ? colorMix(chartThemeColor[0], '#ffffff', 0.9) : colorMix(chartThemeColor[0], '#ffffff', 0.8) }
      ]
    } else {
      minAverage = 4
      pieces = [{ lt: minAverage, label: '0-' + minAverage, color: isMap && isPrimary ? colorMix(chartThemeColor[0], '#ffffff', 0.9) : colorMix(chartThemeColor[0], systemConfig.value.isLight ? '#ffffff' : '#000000', 0.8) }]
    }
    let customVisualMap = {}
    if (XEUtils.isObject(initOptions.visualMap)) {
      customVisualMap = initOptions.visualMap
    }
    const initVisualMap = {
      type: 'piecewise',
      dimension: 0,
      pieces: pieces,
      textStyle: {
        color: systemConfig.value.isLight ? '#6e7079' : 'rgba(255,255,255,.5)'
      }
    }
    initOptions.visualMap = deepMerge(customVisualMap, initVisualMap)
    if (isMap) {
      initOptions.series[0].itemStyle.areaColor = systemConfig.value.isLight ? '#eeeeee' : 'rgba(0,0,0,.1)'
    }
  }
  return initOptions
}
